//index.js
const app = getApp()

Page({
  data: {
    avatarUrl: './user-unlogin.png',
    userName:'点击头像\n进行授权',
    userInfo: {},
    logged: false,
    // takeSession: false,
    // requestResult: ''
    step: 1,
    counterId: '',
    openid: '',
    count: null,
    queryResult: '',
  },

  onLoad: function(options) {
    if (app.globalData.openid) {
      this.setData({
        openid: app.globalData.openid
      })
    }
    if (this.data.step === 1 && !this.data.openid) {
      wx.cloud.callFunction({
        name: 'login',
        data: {},
        success: res => {
          app.globalData.openid = res.result.openid
          this.setData({
            step: 2,
            openid: res.result.openid
          })
        },
        fail: err => {
          wx.showToast({
            icon: 'none',
            title: '获取 openid 失败，请检查是否有部署 login 云函数',
          })
          console.log('[云函数] [login] 获取 openid 失败，请检查是否有部署云函数，错误信息：', err)
        }
      })
    } else {
      const callback = this.data.step !== 6 ? function () { } : function () {
      console.group('数据库文档')
      console.log('https://developers.weixin.qq.com/miniprogram/dev/wxcloud/guide/database.html')
      console.groupEnd()
    }

      this.setData({
        step: this.data.step + 1
      }, callback)
    }
    // 获取用户信息
    wx.getSetting({
      success: res => {
        if (res.authSetting['scope.userInfo']) {
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
          wx.getUserInfo({
            success: res => {
              this.setData({
                avatarUrl: res.userInfo.avatarUrl,
                userInfo: res.userInfo,
                userName: res.userInfo.nickName
              })
            }
          })
        }
      }
    })
  },

  onGetUserInfo: function(e) {
    if (!this.logged && e.detail.userInfo) {
      this.setData({
        logged: true,
        avatarUrl: e.detail.userInfo.avatarUrl,
        userInfo: e.detail.userInfo,
        userName: e.detail.userInfo.nickName
      })
    }
    var openid = this.data.openid;
    this.onQuery();
    // this.onAdd();
  },

  
  onAdd: function () {
    if (app.globalData.openid) {
      this.setData({
        openid: app.globalData.openid
      })
    }
    //添加
    const db = wx.cloud.database()
    db.collection('counters').add({
      data: {
        count: 1,
        sign: 1,
        select: {
          way: 0,
          difficulty: 0,
          nine: [true, true, false,
            false, false, false,
            false, false, false]
        },
        vip: false,
        balance: 0
      },
      success: res => {
        // 在返回结果中会包含新创建的记录的 _id
        this.setData({
          counterId: res._id,
          count: 1,
          sign: 1,
          select:{
            way:0,
            difficulty:0,
            nine: [true, true, false, 
            false, false, false, 
            false, false, false]
          },
          vip:false,
          balance:0
        })
        wx.showToast({
          title: '新增记录成功',
        })
        console.log('[数据库] [新增记录] 成功，记录 _id: ', res._id)
      },
      fail: err => {
        wx.showToast({
          icon: 'none',
          title: '新增记录失败'
        })
        console.error('[数据库] [新增记录] 失败：', err)
      }
    })
  },
  onQuery: function () {
    const db = wx.cloud.database()
    // 查询当前用户所有的 counters
    db.collection('counters').where({
      _openid: this.data.openid
    }).get({
      success: res => {
        this.setData({
          queryResult: JSON.stringify(res.data, null, 2)
        })
        var length = res.data.length;
        if(length==0){
          this.onAdd();
        }
        console.log('[数据库] [查询记录] 成功: ', res)
      },
      fail: err => {
        wx.showToast({
          icon: 'none',
          title: '查询记录失败'
        })
        console.error('[数据库] [查询记录] 失败：', err)
      }
    })
  },

  notOpen: function () {
    //暂未开放
    wx.showModal({
      title: '提示',
      content: '暂未开放,敬请期待！',
    })
  }
})
